package com.lplb.gateway.filter;


import com.lplb.gateway.config.properties.AuthProperties;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.Charsets;
import org.reactivestreams.Publisher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * 响应参数过滤器，最先执行, order必须小于-1
 *
 * @author ws
 * @mail 1720696548@qq.com
 * @date 2020/2/13 0013 10:48
 */
@Component
@NoArgsConstructor
@Slf4j
@SuppressWarnings("all")
public class ResponseFilter implements GlobalFilter, Ordered {
    // 过滤执行顺序，负数可获取正常的url请求接口，大于等于0接口前服务名将被过滤
    @Override
    public int getOrder() {
        return -1;
    }

    @Autowired
    private AuthProperties authProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        try {
            ServerHttpResponse originalResponse = exchange.getResponse();
            DataBufferFactory bufferFactory = originalResponse.bufferFactory();
            ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
                @Override
                public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                    if (body instanceof Flux) {
                        Flux<? extends DataBuffer> fluxBody = (Flux<? extends DataBuffer>) body;
                        return super.writeWith(fluxBody.buffer().map(dataBuffers -> {
                            DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
                            DataBuffer join = dataBufferFactory.join(dataBuffers);
                            byte[] content = new byte[join.readableByteCount()];
                            join.read(content);
                            DataBufferUtils.release(join);
                            String responseData = new String(content, Charsets.UTF_8);
                            responseData = responseData.replaceAll(":null", ":\"\"");
                            byte[] uppedContent = responseData.getBytes(Charsets.UTF_8);
                            // 进行xss过滤，不处理swagger文档,v2/api-docs
                            if (authProperties.isXssRespAttack() && responseData.toString().indexOf("v2/api-docs") == -1) {
                                responseData = ResponseFilter.htmlEncode(responseData);
                            }
                            //
                            log.debug("响应数据:{}", responseData);
                            return bufferFactory.wrap(uppedContent);
                        }));
                    } else {
                        return chain.filter(exchange);
                    }
                }
            };
            // replace response with decorator
            return chain.filter(exchange.mutate().response(decoratedResponse).build());
        } catch (Exception e) {
            log.error(" ReplaceNullFilter 异常", e);
            return chain.filter(exchange);
        }
    }


    /**
     *  Html 文本特殊符号转换，防止 xss攻击字符转换配置工具类
     *
     * @param source
     * @return java.lang.String
     * @author ws
     * @mail 1720696548@qq.com
     * @date 2020/2/9 0009 16:31
     */
    public static String htmlEncode(String source) {
        if (source == null) {
            return "";
        }
        String html = "";
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < source.length(); i++) {
            char c = source.charAt(i);
            switch (c) {
                case '<':
                    buffer.append("&lt;");
                    break;
                case '>':
                    buffer.append("&gt;");
                    break;
                case '&':
                    buffer.append("&amp;");
                    break;
//                case '"':
//                    buffer.append("&quot;");
//                    break;
                default:
                    buffer.append(c);
            }
        }
        html = buffer.toString();
        return html;
    }
}